package com.jeeplus.modules.monitor.task;


import com.jeeplus.modules.memberorder.entity.MemberOrder;
import com.jeeplus.modules.memberorder.service.MemberOrderService;
import com.jeeplus.modules.monitor.entity.Task;
import lombok.extern.slf4j.Slf4j;
import org.quartz.DisallowConcurrentExecution;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

@Slf4j
@DisallowConcurrentExecution
public class OrderTask extends Task {

    @Autowired
    private MemberOrderService memberOrderService;

    /**
     * 订单7天倒计时收货
     */
    @Override
    public void run() {
        MemberOrder memberOrder = new MemberOrder();
        memberOrder.setOrderState("3");
        List<MemberOrder> list = memberOrderService.findList(memberOrder);
        List<MemberOrder> dataList = new CopyOnWriteArrayList<>();
        for (MemberOrder order : list) {
            long surplusTime = getSurplusTime(order.getDeliveryTime());
            if (surplusTime == 0) {
                order.setOrderState("4");
                order.setTakeDate(new Date());
                dataList.add(order);
            }
        }
        // 执行订单保存操作
        memberOrderService.takeOrder(dataList);
        log.info("执行订单自动收货定时任务");
    }

    /**
     * 计算剩余的毫秒值
     * @param date 开始日期
     * @return 剩余的毫秒值
     */
    public long getSurplusTime(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DATE, 7);
        long start = new Date().getTime();// 当前时间的毫秒值
        long end = cal.getTime().getTime();// 结束时间的毫秒值
        return (end - start) < 0 ? 0 : (end - start);
    }
}